﻿using System.IO;
using System.Windows;
using Microsoft.Win32;

namespace Infrastructure.Helpers
{
    public static class OpenFileDialogHelper
    {
        /// <summary>
        /// 打开一个对话框供用户选择 Excel 文件，并返回所选文件的路径。
        /// 如果用户取消选择，则返回 null。
        /// </summary>
        /// <returns>所选文件的完整路径，或 null（如果未选择文件）。</returns>
        public static string SelectExcelFile()
        {
            var dialog = CreateOpenFileDialog("Excel documents(*.xlsx)|*.xlsx", ".xlsx");
            dialog.Title = "选择文件";
            dialog.CheckFileExists = true;

            if (dialog.ShowDialog() != true)
            {
                return null;
            }
            return dialog.FileName;
        }


        /// <summary>
        /// 创建用于打开图像文件的 OpenFileDialog。
        /// 支持的文件类型包括：BMP、JPG、JPEG 和 PNG。
        /// </summary>
        /// <returns>配置好的 OpenFileDialog 实例。</returns>
        public static OpenFileDialog CreateOpenImageFileDialog()
        {
            return CreateOpenFileDialog("Image Files (*.bmp, *.jpg, *.jpeg, *.png)|*.bmp;*.jpg;*.jpeg;*.png;");
        }



        /// <summary>
        /// 创建用于打开模板文件（XML 格式）的 OpenFileDialog。
        /// </summary>
        /// <returns>配置好的 OpenFileDialog 实例。</returns>
        public static OpenFileDialog CreateOpenTemplateFileDialog()
        {
            return CreateOpenFileDialog("Template Files (*.xml)|*.xml;");
        }

        /// <summary>
        /// 创建用于打开 Excel 文件的 OpenFileDialog。
        /// 支持的文件类型包括：XLSX 和 XLS。
        /// 默认扩展名为 .xlsx。
        /// </summary>
        /// <returns>配置好的 OpenFileDialog 实例。</returns>
        public static OpenFileDialog CreateOpenExcelFileDialog()
        {
            return CreateOpenFileDialog("Excel documents|*.xlsx;*.xls", ".xlsx");
        }

        private static OpenFileDialog CreateOpenFileDialog(string filter, string defaultExt = null)
        {
            return new OpenFileDialog
            {
                Filter = filter,
                DefaultExt = defaultExt
            };
        }

        /// <summary>
        /// 创建用于保存图像文件的 SaveFileDialog。
        /// 支持的文件类型包括：BMP、JPG、JPEG 和 PNG。
        /// </summary>
        /// <returns>配置好的 SaveFileDialog 实例。</returns>
        public static SaveFileDialog CreateSaveImageFileDialog()
        {
            return CreateSaveFileDialog("Image Files (*.bmp, *.jpg, *.jpeg, *.png)|*.bmp;*.jpg;*.jpeg;*.png;", false);
        }

        private static SaveFileDialog CreateSaveFileDialog(string filter, bool overwritePrompt = true, string defaultExt = null)
        {
            return new SaveFileDialog
            {
                Filter = filter,
                OverwritePrompt = overwritePrompt,
                DefaultExt = defaultExt
            };
        }

        #region 选择文件夹
        /// <summary>
        /// 选择文件夹路径（经典 WinForms 方案）
        /// </summary>
        /// <param name="defaultPath">默认路径</param>
        /// <param name="title">对话框标题</param>
        public static string SelectFolderPath()
        {
            var folderDialog = new OpenFolderDialog
            {
                Title = "Select Folder",
                //InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)
                InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
            };

            if (folderDialog.ShowDialog() == true)
            {
                var folderName = folderDialog.FolderName;
                MessageBox.Show($"You picked ${folderName}!");
                return folderName;
            }
            return string.Empty;

        }



        /// <summary>
        /// 验证路径有效性 
        /// </summary>
        public static bool ValidatePath(string path, bool checkWritePermission = false)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(path)) return false;

                var dir = Path.GetDirectoryName(path);
                if (!Directory.Exists(dir)) return false;

                return !checkWritePermission || HasWritePermission(dir);
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 检查目录写入权限 
        /// </summary>
        private static bool HasWritePermission(string folderPath)
        {
            try
            {
                var testFile = Path.Combine(folderPath, Guid.NewGuid().ToString());
                File.WriteAllText(testFile, string.Empty);
                File.Delete(testFile);
                return true;
            }
            catch
            {
                return false;
            }
        }
        #endregion


    }
}
